package com.star.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.star.constant.MessageConstant;
import com.star.constant.StatusConstant;
import com.star.context.BaseContext;
import com.star.dto.DishDTO;
import com.star.dto.DishPageQueryDTO;
import com.star.entity.Category;
import com.star.entity.Dish;
import com.star.entity.DishFlavor;
import com.star.exception.BaseException;
import com.star.exception.DeletionNotAllowedException;
import com.star.mapper.CategoryMapper;
import com.star.mapper.DishFlavorMapper;
import com.star.mapper.DishMapper;
import com.star.mapper.SetmealDishMapper;
import com.star.result.PageResult;
import com.star.service.DishService;
import com.star.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional               // 事务注解要么同时成功，要么同时失败
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 新增菜品默认停售
        dish.setStatus(StatusConstant.DISABLE);
        // 默认商家id
        dish.setBusinessId(BaseContext.getCurrentId());
        // 公共字段自动注入 create_time,create_user,update_time,update_user

        dishMapper.insert(dish);
        // 获取insert后生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if(!dishFlavorList.isEmpty() && dishFlavorList != null){
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            // 批量插入口味数据
            dishFlavorMapper.insertBatch(dishFlavorList);
        }
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        // 根据菜品id查询菜品数据
        Dish dish = dishMapper.getById(id);
        if(dish == null){
            throw new BaseException("菜品不存在");
        }
        Category category = categoryMapper.getById(dish.getCategoryId());
        // 根据菜品id查询口味数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        dishVO.setCategoryName(category.getName());
        return dishVO;
    }

    /**
     * 根据菜品分类查询菜品
     * @param dish
     * @return
     */
    public List<Dish> getByCategoryId(Dish dish) {
        return dishMapper.getByDish(dish);
    }

    /**
     * 更新菜品和对应的口味数据
     * @param dishDTO
     */
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 修改菜品表基本数据
        dishMapper.update(dish);
        // 修改对应的口味数据 先删除再修改
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if(!dishFlavorList.isEmpty() && dishFlavorList != null){
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            // 批量插入口味数据
            dishFlavorMapper.insertBatch(dishFlavorList);
        }
    }

    /**
     * 更新菜品起售、停售状态
     * @param status
     * @param id
     */
    public void updateStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                // 启售中的菜品不删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 被套餐关联的菜品不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishId(ids);
        if(!setmealIds.isEmpty()){
            // 当前菜品被套餐关联，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
//        // 删除菜品表的数据
//        for (Long id : ids) {
//            dishMapper.delete(id);
//            // 关联的口味数据也要删除
//            dishFlavorMapper.deleteByDishId(id);
//        }

        // 根据菜品id集合批量删除菜品数据
        dishMapper.deleteByIds(ids);
        // 根据菜品id集合批量删除口味数据
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 用户端
     */
    /**
     * 根据菜品查询菜品和口味数据列表
     * @param dish
     * @return
     */
    public List<DishVO> getByDishWithFlavors(Dish dish) {
        List<Dish> dishList = dishMapper.getByDish(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            String categoryName = categoryMapper.getById(d.getCategoryId()).getName();
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            // 根据菜品id查询对应口味数据
            List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(dishFlavorList);
            dishVOList.add(dishVO);
            dishVO.setCategoryName(categoryName);
        }
        return dishVOList;
    }
}
